<?php
class StarsController extends AppController {

	var $name = 'Stars';
	
/*	public $error = array();					//array of error messages
	public $warning = '';						//array of warning messages

	private $twitteverest = array();			//datas of the stars
 */

	private $cp = null;							//curl pointer
	private $getFriendsIdUrl = 'http://twitter.com/friends/ids/';		//twitter api url for getting id-s
	private $getFriendsDataUrl = 'http://twitter.com/users/show/';		//titter api url for getting user datas
	private $twResponseFormat = 'json';		//twitter api response format
	private $httpok = array(200, 304);		//http status codes if there is no error
	private $httpNotFound = 404;				//requested url not exists - username error
	private $curlCount = 0;						//number og curl requests

	public $starCount = 0;						//we show this many stars
	public $starCountAll = 0;					//all found stars
	public $twOrder = 'followers_count';		//stars are ordered by this
	public $starPerPage = 10;					//this many star will be shown in a page
	public $maxStarPage = 4;					//maximum requested user number is $this->starPerPage * $this->$maxStarPage if we found more we throw a warning and show $this->starPerPage user shuffled
	public $starIds = array();					//the id-s os the stars

	function index(){
		$this->Star->query('SET wait_timeout = 120');
		if(isset($this->params['url']['theNames'])){
			$users = trim(str_replace(', ', ',', htmlentities(str_replace('@', '', $this->params['url']['theNames']))));
			$users = preg_replace('/[ ,]/', '*', $users);
			$users = explode('*', $users);
		}
		else
			$users =  $this->Session->read('twitteverest.users');


//todo: sanitize


		//ugyanabban a lekérésben vagyunk? használjuk a session adatokat új lekérés helyett
		if($users != $this->Session->read('twitteverest.users')){
			$twitteverest = $this->_getTwitteverest($users);
			//put results to the DB
/*			foreach($twitteverest as $t){
				$t = array(
						'Star' => array(
										'id' => $t->id,
										'name' => $t->screen_name,
										'friends' => 
										)
						);
			}*/
			//$twitteverest = array_merge($t, $twitteverest);	//azonos indexek felülíródnak?
				//debug($twitteverest);
				/*
				[13] => stdClass Object
		        (
	            [description] => 
		         [url] => 
		         [name] => zoltan visy
		         [protected] => 
		         [status] => stdClass Object
		             (
	                 [truncated] => 
                    [in_reply_to_status_id] => 
                    [text] => nyertünk a stratégiai tréning versenyén: legjobb prezi egy fiktív tivo kampányra.
                    [in_reply_to_user_id] => 
                    [favorited] => 
                    [created_at] => Fri Mar 27 17:57:20 +0000 2009
                    [id] => 1402373836
                    [source] => Netvibes
                )
					[profile_image_url] => http://s3.amazonaws.com/twitter_production/profile_images/32840022/sapesz_normal.jpg
					[location] => Budapest
					[id] => 4871451
					[followers_count] => 15
					[screen_name] => misizoli
					)
				[warning] => Too much stars! (172) Please add some more to the search box.
				*/
			$this->Session->write('twitteverest.stars', $twitteverest);
			$this->Session->write('twitteverest.starIds', $this->starIds);
			$this->Session->write('twitteverest.users', $users);
			$this->Session->write('twitteverest.starCount', $this->starCount);
			$this->Session->write('twitteverest.starCountAll', $this->starCountAll);
			$this->Session->write('twitteverest.starPerPage', $this->starPerPage);
		}

		$page = isset($this->params['url']['page']) ? $this->params['url']['page'] : 1;
		$this->set('page', $page);
			
		$this->set('userList', implode(' ', $this->Session->read('twitteverest.users')));
		//debug($this->curlCount);
		//debug($twitteverest);
		//debug($this->Session->read());
	}
	
	private function _getTwitteverest($users){
		$data = $this->_getData($users);
		//debug($data);
		if(isset($data['error']))
			return $data;
		else if($data){
			$warning = false;
			if(isset($data['warning'])){
				$warning = $data['warning'];
				unset($data['warning']);
			}
			usort($data, array('StarsController', '_sort'));
			if($warning)
				$data['warning'] = $warning;
			return $data;
		}
		else
			return false;
	}
	
	private function _getData($users){
		//Initialize the Curl session
		$this->cp = curl_init();
		//Set curl to return the data instead of printing it to the browser.
		curl_setopt($this->cp, CURLOPT_RETURNTRANSFER, true);
		$twError = $friends = $friendsIds = array();
		foreach($users as $userName){
			$user_friends = $this->_getFriendsIds($userName);
			//debug($user_friends);
			if(!$user_friends){
				//a user nem is létezik
				//dobunk egy warningot és továbblépünk
				$friends['warning']['userDoesNotExists'][] = $userName;
			}
			elseif(!isset($user_friends['error']))
				$friendsIds = (!count($friendsIds)) ? $user_friends : array_intersect($user_friends, $friendsIds);
			else
				array_push($twError, $user_friends['error']);
		}
		//print count($friendsIds) . ' > ' . $this->maxStarPage*$this->starPerPage;
		//debug($friendsIds);				//friendsIds is the joint with maybe a few thousand star ids

		if(!count($twError)){
			$this->starCountAll = $fC = count($friendsIds);
			if($fC > $this->maxStarPage*$this->starPerPage){
				//we have more stars than we could get from twitter api so we cut the response array to a smaller chunk
				shuffle($friendsIds);
				$friendsIds = array_slice($friendsIds, 0, $this->starPerPage);
				$friends['warning']['tooMuchStars'] = $fC;
			}
			//debug($friendsIds);
			if(!empty($friendsIds)){
				sort($friendsIds);			//reindexing $friendsIds
				$this->starCount = $starCount = count($friendsIds);		//starCount maximalixed above to $this->maxStarPage*$this->starPerPage
				for($i = 0; $i < $starCount; $i++){
					//getting stars
					$f = $this->_getFriends($friendsIds[$i]);
					if(!isset($f->error))
						array_push($friends, $f);
					else
						array_push($twError, $f->error);
				}
			$this->starIds = $friendsIds;
			}
			//debug($friends);
			//debug($twError);
		}
		//Close the connection
		curl_close($this->cp);
		//if we do not have errors but not friend than the users do not have joint
		if(empty($friends) && !count($twError))
			return(array('warning' => 'noJointStars'));
		return(empty($friends) ? array('error' => $twError) : $friends);
	}
	
	private function _sort($a, $b){
		//$order = $this->twOrder;
		$order = 'followers_count';
		return(($a->$order < $b->$order) ? 1 : -1);
	}

	private function _getFriendsIds($userName){
		$twError = array();
		$error = false;
		$url = $this->getFriendsIdUrl . $userName . '.' . $this->twResponseFormat;
		//Set the URL
		curl_setopt($this->cp, CURLOPT_URL, $url);
		//Execute the fetch
		$data = json_decode(curl_exec($this->cp));
		$this->curlCount++;
		$status = curl_getinfo($this->cp, CURLINFO_HTTP_CODE);
		if(!in_array(substr($status, 0, 3), $this->httpok)){
			if($status == $this->httpNotFound)
				return false;
			else{
				array_push($twError, '_getFriendsIds(' . $userName . ') :: ' . $status);
				$error = true;
			}
		}
		if(isset($data->error)){
			array_push($twError, '_getFriendsIds(' . $userName . ') :: ' . $data->error);
			$error = true;
		}
		//debug($data);
		//debug($error);
		return $error ? array('error' => $twError) : $data;	
	}
	
	private function _getFriends($id){
		$error = false;
		$twError = $names = array();
		//ha a user szerepel a DB-ben kérjük le onnan az adatait
		$data = $this->Star->find('first', array(
												'conditions' => array(
																		'id' => $id,
																		'requested >=' => (date('Y-m-d H:i:s', time()-3*24*60*60))
																		),
												'recursive' => -1
												));
		$data = unserialize($data['Star']['userdata']);
		if(!$data){
			curl_setopt($this->cp, CURLOPT_URL, $this->getFriendsDataUrl . $id . '.' . $this->twResponseFormat);
			$data = curl_exec($this->cp);
			$this->curlCount++;
			$status = curl_getinfo($this->cp, CURLINFO_HTTP_CODE);
			if(!in_array(substr($status, 0, 3), $this->httpok)){
				array_push($twError, '_getFriends(' . $id . ') :: ' . $status);
				$error = true;
			}
			else
				$data = (json_decode($data));
			
			if(isset($data->error)){
				array_push($twError, '_getFriends(' . $id . ') :: ' . $data->error);
				$error = true;
			}
			else{
				//no error put user to the DB
				$star = array('Star' => array(
												'id' => $data->id,
												'name' => $data->screen_name,
												'requested' => date('Y-m-d H:i:s'),
												'userdata' => serialize($data)
												));
				$this->Star->id = $data->id;
				$this->Star->save($star);
			}
		}
		//debug($data);
		/*
		 
		 stdClass Object
(
    [statuses_count] => 6336
    [profile_background_tile] => 
    [profile_link_color] => 9D582E
    [description] => 
    [utc_offset] => 3600
    [profile_sidebar_fill_color] => EADEAA
    [profile_background_image_url] => http://static.twitter.com/images/themes/theme8/bg.gif
    [friends_count] => 78
    [following] => 
    [time_zone] => Budapest
    [profile_sidebar_border_color] => D9B17E
    [followers_count] => 270
    [url] => http://tothbenedek.hu/
    [name] => Benedek Toth
    [protected] => 
    [status] => stdClass Object
        (
            [truncated] => 
            [text] => @dw1: lekapcsoltam a billentyűzetvilágítást juteszembe :)
            [in_reply_to_status_id] => 
            [in_reply_to_user_id] => 251703
            [favorited] => 
            [created_at] => Sat Mar 28 19:37:59 +0000 2009
            [id] => 1408423395
            [source] => <a href="http://turulcsirip.hu/">Turulcsirip</a>
        )

    [notifications] => 
    [profile_background_color] => 8B542B
    [created_at] => Tue Jan 30 19:20:52 +0000 2007
    [profile_image_url] => http://s3.amazonaws.com/twitter_production/profile_images/21952292/mepic__m_solat__normal.jpg
    [favourites_count] => 0
    [profile_text_color] => 333333
    [location] => Budapest
    [id] => 733893
    [screen_name] => tothbenedek
)

														 */
		if($error){
			$data = new stdClass();
			$data->error = $twError;
		}
		return $data;
	}
	
	function feedback(){
		//sending feedbacks
		if($this->data){
			$message = $this->data['Star']['message'] . "\n--------------\n" . $_SERVER['HTTP_USER_AGENT'] . "\n--------------\n" . var_export($this->Session->read('twitteverest.stars.error'), true);
			$this->Email->from = $this->data['Star']['email'] ? $this->data['Star']['email'] : 'Twitteverest user <twitteverest@webmania.cc>';
			$this->Email->to = 'rrd <rrd@1108.cc>';
			$this->Email->subject = 'Twitteverest feedback';
			$this->Email->send($message);
			$this->set('feedbacked', true);
		}
	}

}

?>